/***************
 * Upload Preview Grid
 *
 * An Ext.grid.GridPanel that previews parsing a csv upload
 */
AIR2.Upload.PreviewGrid = function() {
    var panel;
    var pgrid = new Ext.grid.GridPanel({
        store: new Ext.data.ArrayStore({autoDestroy: true}),
        columns: [
            {header: 'Column 1'},
            {header: 'Column 2'},
            {header: 'Column 3'},
            {header: 'Column 4'},
        ],
        stripeRows: true,
        enableHdMenu: false,
        disableSelection: true,
        enableColumnHide: false,
        enableColumnMove: false,
        loadMask: true,
        height: 125,
        reset: function() {
            this.reconfigure(
                new Ext.data.ArrayStore({autoDestroy: true}),
                new Ext.grid.ColumnModel({
                    columns: [
                        {header: 'Column 1'},
                        {header: 'Column 2'},
                        {header: 'Column 3'},
                        {header: 'Column 4'},
                    ]
                })
            );
        },
        /* load a preview */
        loadPreview: function(uuid, alreadyValid) {
            if (this.ajaxId) {
                Ext.Ajax.abort(this.ajaxId);
                this.ajaxId = false;
            }

            // fire the remote request
            if (this.loadMask.show) this.loadMask.show();
            this.ajaxId = Ext.Ajax.request({
                url: AIR2.HOMEURL+'/upload/'+uuid+'/preview.json?z=4',
                scope: this,
                callback: function(opts, success, resp) {
                    this.ajaxId = false;
                    if (this.loadMask.hide) this.loadMask.hide();

                    var statusFld = this.ownerCt.get(0);
                    if (success) {
                        var data = Ext.util.JSON.decode(resp.responseText);
                        pgrid.prevDtim = data.radix.tank_upd_dtim;
                        if (data.success) {
                            statusFld.clearInvalid();
                            statusFld.setValue('Total: '+data.lines);
                            panel.fireEvent('afterpreview', true, data);
                        }
                        else {
                            statusFld.markInvalid(data.message);
                            panel.fireEvent('afterpreview', false, data);
                        }

                        // reload the preview grid
                        this.reconfigureGrid(data.header, data.preview);
                    }
                    else {
                        statusFld.markInvalid('Encountered a server error');
                    }
                }
            });
        },
        /* helper function to define a preview column */
        reconfigureGrid: function(header, rows) {
            // create grid column/field defs
            var cdefs = [], fdefs = [];
            this.hasInvalidHeaders = false;
            for (var i=0; i<header.length; i++) {
                var dataIdx = 'col'+(i+1);
                var h = header[i].name;
                if (!header[i].valid) {
                    h = '<b style="color:red;font-style:italic;">'+h+'</b>';
                    this.hasInvalidHeaders = true;
                }

                fdefs[i] = dataIdx;
                cdefs[i] = {header: h, dataIndex: dataIdx};
            }

            // reconfigure the preview grid
            this.reconfigure(
                new Ext.data.ArrayStore({autoDestroy: true, fields: fdefs, data: rows}),
                new Ext.grid.ColumnModel({columns: cdefs})
            );
            this.autoSizeColumns(rows.length, cdefs.length);
        },
        /* auto-size the columns based on content */
        autoSizeColumns: function(numRows, numCols) {
            for (var col=0; col<numCols; col++) {
                var width = 0;
                for (var row=0; row<numRows; row++) {
                    var el = this.view.getCell(row, col);
                    width = Math.max(width, Ext.fly(el.firstChild).getTextWidth());
                }

                // check against the header widths
                var hdr = this.view.getHeaderCell(col);
                width = Math.max(width, Ext.fly(hdr.firstChild).getTextWidth());

                // check minimum and maximum col width
                width = width + 14; //pad
                width = Math.max(width, 50); //min 50
                width = Math.min(width, 150); //max 150
                this.colModel.setColumnWidth(col, width);
            }
        }
    });

    panel = new Ext.form.FormPanel({
        cls: 'air2-upload-preview',
        unstyled: true,
        padding: '2px 20px',
        items: {
            xtype: 'fieldset',
            title: 'Preview',
            items: [{
                xtype: 'displayfield',
                cls: 'upload-preview-msg',
                hideLabel: true,
                msgTarget: 'under'
            }, pgrid]
        },
        setTankData: function(data) {
            var meta = (data) ? Ext.decode(data.tank_meta) : {};
            if (meta.valid_file) {
                // record the upd_dtim of the record we're previewing
                var dtim = data.tank_upd_dtim;
                if (dtim != pgrid.prevDtim) {
                    pgrid.loadPreview(data.tank_uuid, meta.valid_header);
                }
            }
            else {
                pgrid.reset();
            }
        }
    });

    return panel;
}